import xml.sax
from constants import *
import os
import subprocess
from ijp import cat_utils
import StringIO
import tempfile
import shutil

class XmlDumpParser(xml.sax.handler.ContentHandler):
    def __init__(self):
        self.dump = None
        self.inFile = None

    def startElement(self, name, attrs):
        if name == "dataset":
            self.name = attrs["name"]
            self.type = attrs["type"]
            self.start = attrs.get("start")
            self.end = attrs.get("end")
            self.id = attrs.get("id")
            self.parameters = {}  # Dictionary of dataset parameters
            self.files = {}  # Dictionary of pairs of type, dictionary_of_file_parameters 
        elif name == "parameter":
            if self.inFile:
                parms = self.files [self.inFile][1]     
            else:
                parms = self.parameters
            parms[attrs["name"]] = attrs["value"]
        elif name == "file":
            self.inFile = attrs["name"]
            self.files [attrs["name"]] = attrs["type"], {}

    def endElement(self, name):
        if name == "file":
            self.inFile = None
            
def getUpperBranches(session, datasetId, dest):
    if not os.path.exists(dest): os.mkdir(dest)
    fdir = tempfile.mkdtemp()
    session.unzipDataset(datasetId, fdir)
    dirName = subprocess.check_output(['find', fdir, '-mindepth', '5', '-maxdepth', '5', '-type', 'd']).strip()
    for adir in os.listdir(dirName):
        shutil.move(os.path.join(dirName, adir), dest)
    shutil.rmtree(fdir)
 
def dumpxml(directory):
    cmd = [XMLDUMP, directory]
    stringOut = StringIO.StringIO()
    stringErr = StringIO.StringIO()
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    mstdout = cat_utils.Tee(proc.stdout, stringOut)
    mstdout.start()
    mstderr = cat_utils.Tee(proc.stderr, stringErr)
    mstderr.start()
    rc = proc.wait()
    if rc != 0: raise Exception(stringErr.getvalue())
    mstdout.join()
    mstderr.join()
    xml_string = stringOut.getvalue()
    dump = XmlDumpParser()
    try:
        xml.sax.parseString(xml_string, dump)
    except xml.sax.SAXException as e:
        raise Exception(str(e) + " returned by " + str(cmd) + " on " + xml_string)
    return dump

def zipDataset(session, path, investigation, dataset_name, dataset_type_name):
    print "path", path
    do = dumpxml(path)
    print do
